package com.hutao.manage.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;  
  

public class PDFUtil {
	
	
	/**
	 * pdf转换成图片
	 * 
	 * @param pdfPathList
	 * @param imagePath
	 * @return
	 */
	public static List<String> pdf2Image(List<String> pdfPathList, String imagePath) {
		List<String> imagePathList = new ArrayList<>();
		
		for (String pdfPath : pdfPathList) {
			File file = new File(pdfPath);
			BufferedImage image = null;
			PDDocument doc = null;
			PDFRenderer renderer = null;
			try {
				doc = PDDocument.load(file);
				renderer = new PDFRenderer(doc);
				int pageCount = doc.getNumberOfPages();
				for (int i = 0; i < pageCount; i++) {
					image = renderer.renderImage(i, 2.5f);
					//String fileName= generateFileNameByTime()+".png";
					String fileName = "";
					try {
						fileName = StringUtil.getTimeId() + ".png";
					} catch (Exception e) {
						e.printStackTrace();
					}
					String imageFileNamePath = imagePath + fileName;
					ImageIO.write(image, "PNG", new File(imageFileNamePath));
					imagePathList.add(fileName);
				}
			} catch (IOException e) {
				return imagePathList = new ArrayList<>();
			} finally {
				if (renderer != null) {
					renderer = null;
				}
				if (doc != null) {
					try {
						doc.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (image != null) {
					image = null;
				}
			}
		}
		return imagePathList;
	}
	
	public static void main(String[] args) {
		File file = new File("C:\\Users\\h2oco2\\Desktop\\D275339-1.pdf");
		BufferedImage image = null;
		PDDocument doc = null;
		PDFRenderer renderer = null;
		String imagePath = "C:\\Users\\h2oco2\\Desktop\\pdf\\";
		try {
			doc = PDDocument.load(file);
			renderer = new PDFRenderer(doc);
			int pageCount = doc.getNumberOfPages();
			for (int i = 0; i < pageCount; i++) {
				image = renderer.renderImage(i, 2.5f);
				//String fileName= generateFileNameByTime()+".png";
				String fileName = "";
				try {
					fileName = i + ".png";
				} catch (Exception e) {
					e.printStackTrace();
				}
				String imageFileNamePath = imagePath + fileName;
				ImageIO.write(image, "PNG", new File(imageFileNamePath));
			}
		} catch (IOException e) {
		} finally {
			if (renderer != null) {
				renderer = null;
			}
			if (doc != null) {
				try {
					doc.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (image != null) {
				image = null;
			}
		}
		
		
	}
	
	public static String generateFileNameByTime() {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		return format.format(new Date());
	}
	
	/**
	 * 
	 * <br>
	 * <p>
	 * Description: 给pdf文件添加水印 <br>
	 * <p><br/>
	 * <p>
	 * 
	 * @param InPdfFile
	 *            要加水印的原pdf文件路径
	 * @param outPdfFile
	 *            加了水印后要输出的路径
	 * @param markImagePath
	 *            水印图片路径
	 * @param imgWidth
	 *            图片横坐标
	 * @param imgHeight
	 *            图片纵坐标
	 * @throws Exception
	 * @see void
	 */
	public static void addPdfImgMark(String InPdfFile, String outPdfFile, String markImagePath,int imgWidth, int imgHeight) throws Exception {  
		PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());  
		PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));  
		
		PdfContentByte under;
		
		PdfGState gs1 = new PdfGState();  
		gs1.setFillOpacity(0.3f);// 透明度设置
	    
		Image img = Image.getInstance(markImagePath);// 插入图片水印
		
		img.setAbsolutePosition(imgWidth, imgHeight); // 坐标
		//img.setRotation(-20);// 旋转 弧度
		//img.setRotationDegrees(45);// 旋转 角度
		// img.scaleAbsolute(200,100);//自定义大小
		img.scalePercent(50);//依照比例缩放
		
		int pageSize = reader.getNumberOfPages();// 原pdf文件的总页数
		for(int i = 1; i <= pageSize; i++) {  
			under = stamp.getUnderContent(i);// 水印在之前文本下
			// under = stamp.getOverContent(i);//水印在之前文本上
			under.setGState(gs1);// 图片水印 透明度
			under.addImage(img);// 图片水印
		}  
		
		stamp.close();// 关闭
		// // 删除不带水印文件
//		File tempfile = new File(InPdfFile);  		
//		if(tempfile.exists()) {  		
//			tempfile.delete();  
//		}  
		
	}  

	

		
		// {projectName=尿比重, examinationResult=1.021, examinationUnit=null, examinationResultMark=, referenceValues=1.003--1.03}, {projectName=尿红细胞, examinationResult=6.60, examinationUnit=p/ul, examinationResultMark=↑, referenceValues=0--5}, {projectName=尿白细胞, examinationResult=739.20, examinationUnit=p/ul, examinationResultMark=↑, referenceValues=0--9}, {projectName=脓细胞, examinationResult=3.96, examinationUnit=p/ul, examinationResultMark=, referenceValues=0--9}, {projectName=结晶, examinationResult=0.00, examinationUnit=p/ul, examinationResultMark=, referenceValues=0--6}, {projectName=二水合草酸钙, examinationResult=0.00, examinationUnit=p/ul, examinationResultMark=, referenceValues=0--6}, {projectName=一水合草酸钙, examinationResult=0.00, examinationUnit=p/ul, examinationResultMark=, referenceValues=0--6}, {projectName=三磷酸盐, examinationResult=0.00, examinationUnit=p/ul, examinationResultMark=, referenceValues=0--6}, {projectName=透明管型, examinationResult=0.00, examinationUnit=p/ul, examinationResultMark=, referenceValues=0--2}, {projectName=病理管型, examinationResult=0.00, examinationUnit=p/ul, examinationResultMark=, referenceValues=0--1.5}, {projectName=非鳞状上皮细胞, examinationResult=0.66, examinationUnit=p/ul, examinationResultMark=, referenceValues=0--2}, {projectName=鳞状上皮细胞, examinationResult=0.66, examinationUnit=p/ul, examinationResultMark=, referenceValues=0--5}, {projectName=酵母菌, examinationResult=70.62, examinationUnit=p/ul, examinationResultMark=↑, referenceValues=0--3}, {projectName=精子, examinationResult=0.00, examinationUnit=p/ul, examinationResultMark=, referenceValues=0--12}, {projectName=滴虫, examinationResult=0.00, examinationUnit=p/ul, examinationResultMark=, referenceValues=0--0.26}]}
		//{title=大便常规+潜血, patientName=黎静, deptCategoryName=重症监护病房内科, specimenCode=5907654266, sexName=女, bedName=5床, barCode=5907654266, ageName=89岁, costName=公费医疗, specimenTypeName=便, mrId=D382, submittingPhysicianName=马劲夫, clinicalDiagnosisName=感染性发热, samplingDateTime=2017-11-15 14:33:00, inspectDateTime=2017-11-16 11:06:24, inspectionDoctorName=韩丽颖, acceptanceCheckDateTime=2017-11-16 11:33:00, reportDateTime=2017-11-16 11:33:32, auditorDoctorName=王兴伟, remark=null, examinationReportsItems=[{projectName=大便潜血试验, examinationResult=阳性, examinationUnit=null, examinationResultMark=, referenceValues=null}, {projectName=大便颜色, examinationResult=棕, examinationUnit=null, examinationResultMark=, referenceValues=null}, {projectName=性状, examinationResult=软, examinationUnit=null, examinationResultMark=, referenceValues=null}, {projectName=粘液, examinationResult=阴性, examinationUnit=null, examinationResultMark=, referenceValues=null}, {projectName=血, examinationResult=阴性, examinationUnit=null, examinationResultMark=, referenceValues=null}, {projectName=虫卵, examinationResult=阴性, examinationUnit=null, examinationResultMark=, referenceValues=null}, {projectName=大便白细胞, examinationResult=0, examinationUnit=/HP, examinationResultMark=, referenceValues=null}, {projectName=大便红细胞, examinationResult=0-1, examinationUnit=/HP, examinationResultMark=, referenceValues=null}, {projectName=脓细胞, examinationResult=0, examinationUnit=/HP, examinationResultMark=, referenceValues=null}, {projectName=其它, examinationResult=/, examinationUnit=null, examinationResultMark=, referenceValues=null}]}


		/**
		 * 生成检验报告单 pdf
		 * @param list
		 * @param homePageTemplatePDFPath
		 * @param targetPath
		 */
		public static void getPdfByTemplate(List<Map<String,Object>> list,String homePageTemplatePDFPath,String targetPath) {
			PdfReader reader = null;
			OutputStream bos = null;
			PdfStamper stamper = null;
			
			try {
				reader = new PdfReader(homePageTemplatePDFPath);// 读取pdf模板
				bos = new FileOutputStream(new File(targetPath));
				stamper = new PdfStamper(reader, bos);
				AcroFields form = stamper.getAcroFields();

				// 使用中文字体
				BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
				ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
				fontList.add(bf);

				form.setSubstitutionFonts(fontList);
				
				for (int i = 0; i < list.size(); i++) {
					Map<String,Object> map = list.get(i);
					String time = "";
					if(map.get("reportDateTime")!=null){
						time=((String)map.get("reportDateTime")).substring(0, 10);
					}
					if(map.get("title")!=null){
						form.setField("title"+i,time + (String)map.get("title"));
					}
					
					form.setField("patientName"+i, (String)map.get("patientName"));
					form.setField("deptCategoryName"+i, (String)map.get("deptCategoryName"));
					form.setField("specimenCode"+i, (String)map.get("specimenCode"));
					form.setField("sexName"+i, (String)map.get("sexName"));
					form.setField("bedName"+i, (String)map.get("bedName"));
					form.setField("barCode"+i, (String)map.get("barCode"));
					form.setField("ageName"+i, (String)map.get("ageName"));
					form.setField("costName"+i, (String)map.get("costName"));
					form.setField("specimenTypeName"+i, (String)map.get("specimenTypeName"));
					form.setField("mrId"+i, (String)map.get("mrId"));
					form.setField("submittingPhysicianName"+i, (String)map.get("submittingPhysicianName"));
					form.setField("clinicalDiagnosisName"+i, (String)map.get("clinicalDiagnosisName"));
					form.setField("samplingDateTime"+i, (String)map.get("samplingDateTime"));
					form.setField("inspectDateTime"+i, (String)map.get("inspectDateTime"));
					form.setField("inspectionDoctorName"+i, (String)map.get("inspectionDoctorName"));
					form.setField("acceptanceCheckDateTime"+i, (String)map.get("acceptanceCheckDateTime"));
					form.setField("reportDateTime"+i, (String)map.get("reportDateTime"));
					form.setField("auditorDoctorName"+i, (String)map.get("auditorDoctorName"));
					form.setField("remark"+i, "本报告仅对监测标本负责");
					
					// {projectName=尿红细胞, examinationResult=6.60, examinationUnit=p/ul, examinationResultMark=↑, referenceValues=0--5}
					List<Map<String,Object>> examList = (List<Map<String, Object>>) map.get("examinationReportsItems");
					for (int j = 0; j < examList.size(); j++) {
						Map<String,Object> examMap = examList.get(j);
						form.setField("projectName"+i+j, (String)examMap.get("projectName"));
						form.setField("examinationResult"+i+j, (String)examMap.get("examinationResult")+"  "+(String)examMap.get("examinationResultMark"));
						form.setField("referenceValues"+i+j, (String)examMap.get("referenceValues"));
					}
				}
				
				stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
				stamper.close();
				
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (Exception e2) {
					}
				}
				if(bos!=null){
					try {
						bos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		
		public static File Pdf(List<String> imgs,String mOutputPdfFileName) {
	        String TAG = "PdfManager";
	        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
	        try {
	            PdfWriter
	                    .getInstance(doc, new FileOutputStream(mOutputPdfFileName));
	            doc.open();
	            for (int i = 0; i < imgs.size(); i++) {
	                doc.newPage();
	                doc.add(new Paragraph("简单使用iText"));
	                Image png1 = Image.getInstance(imgs.get(i));
	                float heigth = png1.getHeight();
	                float width = png1.getWidth();
	                int percent = getPercent2(heigth, width);
	                png1.setAlignment(Image.MIDDLE);
	                png1.scalePercent(percent+3);// 表示是原来图像的比例;
	                doc.add(png1);
	            }
	            doc.close();
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (DocumentException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	 
	        File mOutputPdfFile = new File(mOutputPdfFileName);
	        if (!mOutputPdfFile.exists()) {
	            mOutputPdfFile.deleteOnExit();
	            return null;
	        }
	        return mOutputPdfFile;
	    }

		
		 /**
	     * 第二种解决方案，统一按照宽度压缩 这样来的效果是，所有图片的宽度是相等的，自我认为给客户的效果是最好的
	     *
	     * @param args
	     */
	    public static int getPercent2(float h, float w) {
	        int p = 0;
	        float p2 = 0.0f;
	        p2 = 530 / w * 100;
	        p = Math.round(p2);
	        return p;
	    }

	    public static ByteArrayOutputStream getOutputStream(List<String> imagePaths) throws MalformedURLException, IOException, DocumentException{
	    	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	    	Document document = new Document(PageSize.A4); 
	    	document.setMargins(0, 0, 0, 0);
	    	PdfWriter.getInstance(document, bos);
			document.open();
			for (String imagePath : imagePaths) {
				Image image = Image.getInstance(imagePath);
				float imageHeight=image.getScaledHeight();
				float imageWidth=image.getScaledWidth();
				int i=0;
				while(imageHeight>PageSize.A4.getHeight()||imageWidth>PageSize.A4.getWidth()){
					image.scalePercent(100-i);
					i++;
					imageHeight=image.getScaledHeight();
					imageWidth=image.getScaledWidth();
				}
				image.setAlignment(Image.ALIGN_CENTER);
				document.newPage();
				document.add(image);
			}
		 	document.close();
		 	return bos;
		}
	    
	    public static synchronized void createPDFByImagePaths(List<String> imagePaths,String outputPDFPath) throws Exception{
			ByteArrayOutputStream baos =getOutputStream(imagePaths);
			File newFile = new File(outputPDFPath);
			if(!newFile.exists()){
				File parentFile = new File(newFile.getParent());
				if(!parentFile.exists()){
					parentFile.mkdirs();
				}
			}
			FileOutputStream fileOutputStream = new FileOutputStream(new File(outputPDFPath));
			fileOutputStream.write(baos.toByteArray());
			fileOutputStream.close();

		}

}
